/*
通过mutation间接更新state的多个方法的对象
 */
import {
  RECEIVE_ADDRESS,
  RECEIVE_CATEGORYS,
  RECEIVE_SHOPS,
  RECEIVE_USER_INFO,
  RECEIVE_USER_RESET,

} from './mutation-types'
import {
  reqAddress,
  reqfoodCategorys, reqLogout,
  reqShops,
  reqUserInfo,
} from '../api'
export default {
  async getAddress({commit,state}){
    //发送异步Ajax请求
    const geohash = state.latitude + ',' + state.longitude
    const res = await reqAddress(geohash)
    //提交一个mutation
    if(res.code===0){
      const address = res.data
      commit(RECEIVE_ADDRESS,{address})
    }
  },

  async getCategorys({commit}){
    //发送异步Ajax请求
    const res = await reqfoodCategorys()
    //提交一个mutation
    if(res.code===0){
      const categorys = res.data
      commit(RECEIVE_CATEGORYS,{categorys})
    }
  },

  async getShops({commit,state}){
    //发送异步Ajax请求
    const {latitude,longtitude} = state
    const res = await reqShops(latitude,longtitude)
    //提交一个mutation
    if(res.code===0){
      const shops = res.data
      commit(RECEIVE_ADDRESS,{shops})
    }
  },

  //同步记录用户信息
  recordUser({commit},userInfo){
    commit(RECEIVE_USER_INFO,{userInfo})
  },
  //异步获取用户信息
  async getUserInfo({commit}){
    const res = await reqUserInfo()
    if (res.code ==0){
      const userInfo = res.data
      commit(RECEIVE_USER_INFO,{userInfo})
    }
  },
  //异步登出
  async logout({commit}){
    const res = await reqLogout()
    if (res.code ==0){
      commit(RECEIVE_USER_RESET)
    }
  }
}
